/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.reuters.rfa.example.omm.gui.viewer;

import java.net.InetAddress;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;

/**
 *
 * @author nitin.parmar
 */
public class UserOptions {
    
    public UserOptions() {
        setDefaultValues();
    }
    
    private void readRfaConnectionConfig() {
        Boolean configLoaded = false;

        // location of application specific parameters
        Preferences appPrefs = Preferences.userRoot().node( appCustomConfigPath );
        userName = appPrefs.get("appUserId", "");

        // location where the connection config is stored
        Preferences prefs = Preferences.userRoot().node( appConnectionPath );

        // if the it's an RSSL connection
        if (prefs.get("connectionType", "").compareTo("RSSL") == 0) {
            
            // get the serverList parameter
            server = prefs.get("serverList", "");
            
            // if the serverList parameter was set
            if (server.compareTo("") != 0) {
                
                // get the portNumber parameter
                portNum = prefs.get("portNumber", "");

                // if the portNumber was set
                if (portNum.compareTo("") != 0) {
                    
                    // location of where the session config is stored
                    prefs = Preferences.userRoot().node( appSessionPath );
                    
                    // get the connectionList in the session this application uses
                    String sess = prefs.get("connectionList", appConnectionName);

                    // if the session value was set
                    if (sess.compareTo(appConnectionName) == 0) {
                        configLoaded = true; // we've now read all the required config
                    }
                }
            }
        }

        // if config was not fully read
        if (configLoaded == false) {
            // set to blanks and defaults
            userName = "";
            server = "";
            portNum = "14002";
        }
    }
    
    public void saveRfaConfigPrefs() {
        // location of application specific parameters
        Preferences appPrefs = Preferences.userRoot().node( appCustomConfigPath );
        
        // save the username value
        appPrefs.put("appUserId", userName);

        // RFA session config tree
        Preferences prefs = Preferences.userRoot().node( appSessionPath );
        
        // set connectionList for the session in the session config tree
        prefs.put("connectionList", appConnectionName);

        // RFA connection config tree
        prefs = Preferences.userRoot().node( appConnectionPath );
        
        // set connection details
        prefs.put("connectionType", "RSSL");
        prefs.put("portNumber", portNum);
        prefs.put("serverList", server);
        
        // if debug options have been set
        if (debugOn == true) {
            // RFA "mountTrace" option set in the RFA connection
            if (mountTrace) { 
                prefs.put("mountTrace", "true");
            }
            else {
                prefs.remove("mountTrace");
            }
            
            // RFA "ipcTraceFlags" option set in the RFA connection
            if (ipcTraceFlags > 0) { 
                prefs.put("ipcTraceFlags", "" + ipcTraceFlags);
            }
            else {
                prefs.remove("ipcTraceFlags");
            }
            
            // RFA "traceMsgDomains" option set in the RFA connection
            if (traceMsgDomains.length() > 0) {
                prefs.put("traceMsgDomains", traceMsgDomains);
            } 
            else {
                prefs.remove("traceMsgDomains");
            }
        } else {
            // if none of the tracing options were set, remove any previously set values
            prefs.remove("mountTrace");
            prefs.remove("ipcTraceFlags");
            prefs.remove("traceMsgDomains");
        }

        // set Java log level if a logging level was selected
        if (logLevel != null) {
            // All RFA Java loggers are under the com.reuters.rfa
            Logger logger = Logger.getLogger("com.reuters.rfa");
            
            logger.setLevel(logLevel);
            Handler[] handlers = logger.getHandlers();

            if (handlers.length == 0) {
                Handler handler = new ConsoleHandler();
                handler.setLevel(logLevel);
                logger.addHandler(handler);
            }

            for (int index = 0; index < handlers.length; index++) {
                handlers[index].setLevel(logLevel);
            }
        }
    }
    
    public void storeAppConfigVals( String newUsername, String newServer, String newPortNum, boolean newOutputToConsole) {
        userName = newUsername;
        server = newServer;
        portNum = newPortNum;
        outputToConsole = newOutputToConsole;
    }
    
    public void storeAppOptionVals (
            String appId,
            String pos,
            boolean pauseResume,
            boolean sortableColumns,
            boolean downloadDataDict,
            String rdmDict,
            String enumDict,
            String dialogFont,
            int dialogFontSize,
            Level logLevel
            ) {
        this.appId = appId;
        this.position = pos;
        this.supportPauseResume = pauseResume;
        this.sortable = sortableColumns;
        this.downloadDicts = downloadDataDict;
        this.rdmFieldDict = rdmDict;
        this.enumTablesDict = enumDict;
        this.dialogFont = dialogFont;
        this.dialogFontSize = dialogFontSize;
        this.logLevel = logLevel;
    }
    
    public void storeTraceOptionVals( 
            boolean mountTrace,
            int ipcTraceFlags,
            String traceMsgDomains
            ) {
        this.mountTrace = mountTrace;
        this.ipcTraceFlags = ipcTraceFlags;
        this.traceMsgDomains = traceMsgDomains;
        
        debugOn = 
                (this.mountTrace)|| 
                (this.ipcTraceFlags > 0) || 
                (this.traceMsgDomains.toString().length() > 0);
    }
        
    private void setDefaultValues() {
        // get user, server and port connection details from RFA config
        readRfaConnectionConfig();
        
        appId = "256";
        try
        {
            position = InetAddress.getLocalHost().getHostAddress() + "/net";
        }
        catch (Exception e)
        {
            position = "";
        }

        outputToConsole = false;
        supportPauseResume = true;
        sortable = false;
        downloadDicts = true;
        rdmFieldDict = "";
        enumTablesDict = "";
        dialogFont = "Monospaced";
        dialogFontSize = 12;
        logLevel = null;
    }
    
    public String getUserName() {
        return userName;
    }
    
    public String getAppId() {
        return appId;
    }
    
    public String getPosition() {
        return position;
    }
    
    public String getServer() {
        return server;
    }
    
    public String getPortNum() {
        return portNum;
    }
    
    public boolean getOutputToConsole() {
        return outputToConsole;
    }
    
    public boolean getSupportPauseResume() {
        return supportPauseResume;
    }
    
    public boolean getSortable() {
        return sortable;
    }
    
    public boolean getDownloadDicts() {
        return downloadDicts;
    }
    
    public String getRdmFieldDict() {
        return rdmFieldDict;
    }
    
    public String getEnumTablesDict() {
        return enumTablesDict;
    }
    
    public String getDialogFont() {
        return dialogFont;
    }
    
    public int getDialogFontSize() {
        return dialogFontSize;
    }
    
    public Level getLogLevel() {
        return logLevel;
    }
    
    public boolean getMountTrace() {
        return mountTrace;
    }
    
    public int getIpcTraceFlags() {
        return ipcTraceFlags;
    }

    public String getTraceMsgDomains() {
        return traceMsgDomains;
    }
    
    public String getSessionName() {
        return appConfigNamespace + "::" + appSession;
    }
    
    public boolean getDebugOn() {
        return debugOn;
    }
    
    static final String rfaConfigRoot = "/com/reuters/rfa/";
    static final String appConfigNamespace = "myNamespace";
    static final String appConnectionName = "ommViewAppCon";
    static final String appSession = "myOMMViewSession";
    static final String appConnectionPath = rfaConfigRoot + appConfigNamespace + "/Connections/" + appConnectionName;
    static final String appSessionPath = rfaConfigRoot + appConfigNamespace + "/Sessions/" + appSession;
    static final String appCustomConfigPath = rfaConfigRoot + appConfigNamespace + "/OMMViewer";
    
    private String userName = "";
    private String appId = "";
    private String position = "";
    private String server = "";
    private String portNum = "";
    private boolean outputToConsole = false;
    
    private boolean supportPauseResume = true;
    private boolean sortable = false;
    private boolean downloadDicts = true;
    private String rdmFieldDict = "";
    private String enumTablesDict = "";
    private String dialogFont = "Monospaced";
    private int dialogFontSize = 12;
    private Level logLevel = null;
    
    private boolean mountTrace = false;
    private int ipcTraceFlags = 0;
    private String traceMsgDomains = "";
    private boolean debugOn = false;
}
